Using Bitwise OR Operator (|)
JavaScript Bitwise OR(|) Operator is used to compare two operands by performing OR operation on individual bits of the operands and returns true even if one of the compared bits is 1.
Syntax:
a | b
Example: In this example, we are using the bitwise OR operator to find whether our given number is even or odd.
function checkOddOrEven(number) {
return (number | 1) === number ? 'Odd' : 'Even';
}
console.log(checkOddOrEven(14));
console.log(checkOddOrEven(17));
Output
Even Odd
JavaScript Program to Check if a Number is Odd or Even
We are going to learn how to check whether the number is Even or Odd using JavaScript. In the number system any natural number that can be expressed in the form of (2n + 1) is called an odd number and if the number can be expressed in the form of 2n is called an even number.
In other words, Those numbers that are completely divisible by 2 (give the remainder 0 after dividing by 2) are known as even numbers and those which divided by 2 and leave a reminder 1 are called odd numbers.
Even = {2k : k ∈ Z}
Odd = {2k + 1 : k ∈ Z}
where k is an integer.
Example:
Input: 2
Output: Even number
Input: 41
Output: Odd Number
There are several methods that can be used to Check if a Number is Odd or Even, which are listed below:
Table of Content
- Approach 1: Using the modulo Operator
- Approach 2: Using Bitwise & Operator
- Approach 3: Using Bitwise OR Operator (|)
- Approach 4: Using Ternary Operator